package main

import (
    "fmt"
    "io"
    "log"
	"net/http"
	"os/exec"
	"os"
	"path/filepath"
    "encoding/json"
    "strings"
    "runtime"
)

type Result struct {
    Code  int
	Msg   string
}

func wakeonlan(w http.ResponseWriter, req *http.Request){

    req.ParseForm()
	ip:=req.FormValue("ip")
	mac:=req.FormValue("mac")

    dir, _ := os.Executable()
    resPath := filepath.Dir(dir)


    fmt.Println("接收到唤醒请求 发送唤醒包")
    
    exe_name := "wakeonlan"
    if runtime.GOOS == "windows" {
        exe_name = "wakeonlan.exe"
    }

    cmd := exec.Command(resPath+"\\"+exe_name, mac, ip)
	
    buf, err := cmd.Output()
    if err != nil {
        fmt.Println(err.Error())
    }
    fmt.Println(string(buf))

    result := Result{0,"发送唤醒请求成功"}
    b, err := json.Marshal(result)
    if err != nil {
        fmt.Println("json err:", err)
    }
	io.WriteString(w, string(b))
}

func substr(s string, pos, length int) string {
	runes := []rune(s)
	l := pos + length
	if l > len(runes) {
		l = len(runes)
	}
	return string(runes[pos:l])
}

func getParentDirectory(dirctory string) string {
	return substr(dirctory, 0, strings.LastIndex(dirctory, "/"))
}

func getCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}
	return strings.Replace(dir, "\\", "/", -1)
}


func main() {
    fmt.Println("启动服务...")

    current_dir := getCurrentDirectory()
    parent_dir := getParentDirectory(current_dir)
    resPath := parent_dir+"\\public"

    // 注册函数，用户连接， 自动调用指定处理函数
	http.HandleFunc("/wakeup", wakeonlan)
	http.Handle("/",http.FileServer(http.Dir(resPath)))

    // 监听绑定
    err := http.ListenAndServe(":12345", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}